package com.liuzy.crawler.util;

import java.io.File;

/**
 * @author liuzy
 * @since 2015年9月17日
 */
public class FileUtil {

	public static String creteDir(String path) {
		File file = new File(path);
		if (!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}
		return path;
	}

	public static String creteOrNewDir(String path) {
		File file = new File(path);
		if (file.isDirectory()) {
			deleteDir(file);
		}
		file.mkdirs();
		return path;
	}

	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		return dir.delete();
	}

	public static String buildFileName(String url) {
		StringBuffer sb = new StringBuffer();
		for (char ch : url.toCharArray()) {
			switch (ch) {
			case '\\':
			case '/':
			case ':':
			case '*':
			case '?':
			case '\"':
			case '<':
			case '>':
			case '|':
				sb.append("_");
				break;
			default:
				sb.append(ch);
				break;
			}
		}
		return sb.toString();
	}

}
